package com.ewzj.bigdata.mvp.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.support.v4.view.ViewPager
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import com.bigkoo.convenientbanner.ConvenientBanner
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator
import com.bigkoo.convenientbanner.listener.OnItemClickListener
import com.bumptech.glide.Glide
import com.bumptech.glide.Priority
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.easyandroidanimations.library.BounceAnimation
import com.easyandroidanimations.library.ShakeAnimation
import com.ewzj.bigdata.R
import com.ewzj.bigdata.app.config.AppKey
import com.ewzj.bigdata.app.extensions.dpToPx
import com.ewzj.bigdata.app.extensions.getScollYDistance
import com.ewzj.bigdata.app.extensions.loadImgwithloading
import com.ewzj.bigdata.app.utils.Apputils
import com.ewzj.bigdata.di.component.DaggerHomeFragmentComponent
import com.ewzj.bigdata.di.module.HomeFragmentModule
import com.ewzj.bigdata.mvp.contract.HomeFragmentContract
import com.ewzj.bigdata.mvp.model.rspbean.*
import com.ewzj.bigdata.mvp.presenter.HomeFragmentPresenter
import com.ewzj.bigdata.mvp.ui.activity.*
import com.ewzj.bigdata.mvp.ui.adapter.HomePageAdapter
import com.ewzj.bigdata.mvp.ui.adapter.HourseTypeAdapter
import com.ewzj.bigdata.mvp.ui.holder.AdHolderView
import com.ewzj.bigdata.mvp.ui.view.NumberAnimTextView
import com.gyf.barlibrary.ImmersionBar
import com.jakewharton.rxbinding2.view.RxView
import com.jess.arms.base.BaseFragment
import com.jess.arms.di.component.AppComponent
import com.jess.arms.utils.DataHelper
import com.jess.arms.utils.DeviceUtils
import com.jess.arms.widget.CustomPopupWindow
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration
import com.yqritc.recyclerviewflexibledivider.VerticalDividerItemDecoration
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.fragment_mine.*
import kotlinx.android.synthetic.main.item_cityandsearchyinying.*
import kotlinx.android.synthetic.main.item_zoom.*
import java.util.concurrent.TimeUnit

/**
 * author:zhangjing
 * 作用:
 * return:
 */
class HomeFragment : BaseFragment<HomeFragmentPresenter>(), HomeFragmentContract.View {
    var popwinow:CustomPopupWindow?=null
    open override fun locationCity(city: String,islocation:Boolean) {
        tv_city.setText(city)
        (hearderview.findViewById(R.id.tv_city)as TextView).setText(city)
    }

    override fun initHomeNumber(rspdata: RspHomeData) {
        var buynum=DataHelper.getStringSF(activity,AppKey.BUY_HIS)
        var rentnum=DataHelper.getStringSF(activity,AppKey.RENT_HIS)
        var tvbuy=hearderview.findViewById(R.id.tv_buynum) as NumberAnimTextView
        var tvrent=hearderview.findViewById(R.id.tv_rentnum) as NumberAnimTextView
        DataHelper.SetStringSF(activity,AppKey.BUY_HIS,rspdata.buy_total.toString())
        DataHelper.SetStringSF(activity,AppKey.RENT_HIS,rspdata.rent_total.toString())
        if (buynum!=null){
            tvbuy.setNumberString(buynum,rspdata.buy_total.toString())
        }else{
            tvbuy.setNumberString(rspdata.buy_total.toString())
        }
        if (rentnum!=null){
            tvrent.setNumberString(rentnum,rspdata.rent_total.toString())
        }else{
            tvrent.setNumberString(rspdata.rent_total.toString())
        }
//        (hearderview.findViewById(R.id.tv_buynum) as TextView).text = rspdata.buy_total.toString()
//        (hearderview.findViewById(R.id.tv_rentnum) as TextView).text = rspdata.rent_total.toString()
    }

    override fun initHomeRecylerveiew(adapter: HomePageAdapter) {
        if (rv_hourse.recyclerView.adapter != null) return
        val zoomview = hearderview.findViewById(R.id.zoom_image_view) as ImageView
        val containerview = hearderview.findViewById(R.id.zoom_header_container) as ViewGroup
        rv_hourse.setAdapter(adapter)
        rv_hourse.setLayoutManager(LinearLayoutManager(activity))
        rv_hourse.setZoomView(zoomview)
        rv_hourse.setHeaderContainer(containerview)

    }

    override fun initTypeRecylerveiew(adapter: HourseTypeAdapter) {
        var layoutManager = GridLayoutManager(activity, 2)
        rvbuytag.layoutManager = layoutManager
        if (rvbuytag.adapter == null) {
            rvbuytag.addItemDecoration(VerticalDividerItemDecoration.Builder(activity).colorResId(R.color.white).size(20.dpToPx(activity)).build())
            rvbuytag.addItemDecoration(HorizontalDividerItemDecoration.Builder(activity).colorResId(R.color.white).size(20.dpToPx(activity)).build())
        }
        rvbuytag.adapter = adapter
    }

    override fun initView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        hearderview = inflater.inflate(R.layout.item_recheader, null, false)
        rvbuytag = hearderview.findViewById(R.id.rv_buytag) as RecyclerView
        return inflater.inflate(R.layout.fragment_home, null, false)
    }

    lateinit var hearderview: View
    lateinit var rvbuytag: RecyclerView

    companion object {
        fun newInstance(): HomeFragment {
            val fragment = HomeFragment()
            val args = Bundle()
            fragment.arguments = args
            return fragment
        }
    }

    override fun initData(savedInstanceState: Bundle?) {
        initlistener()
        mPresenter.inithourseType()
        mPresenter.initHeaderview(hearderview)
        mPresenter.getAdData()
//        弹窗广告数据
        mPresenter.getpopAddata()
        var spcity = DataHelper.getStringSF(activity, AppKey.LOCATION_CITY)
        if (spcity.isNullOrEmpty()) return
        mPresenter.initListdata()
//        mPresenter.initListdata()
    }

    override fun setData(data: Any?) {

    }

    override fun onResume() {
        super.onResume()
        if (!DeviceUtils.hasInternet(activity)){
            hearderview.findViewById(R.id.zoom_image_view).visibility=View.VISIBLE
            hearderview.findViewById(R.id.rl_banner).visibility=View.GONE
        }
        mPresenter.onResume()
    }
    override fun setupFragmentComponent(appComponent: AppComponent?) {
        DaggerHomeFragmentComponent.builder().appComponent(appComponent)
                .homeFragmentModule(HomeFragmentModule(this))
                .build().inject(this)
    }

    override fun showLoading() {

    }

    override fun launchActivity(intent: Intent?) {
        startActivity(intent)
    }

    override fun hideLoading() {

    }

    override fun killMyself() {

    }

    override fun showMessage(message: String?) {

    }

    override fun onDestroy() {
        super.onDestroy()
    }

    fun initlistener() {
        rv_hourse.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                if (Math.abs(recyclerView!!.getScollYDistance()) >= 200.dpToPx(activity)) {
                    ll_stickview1.visibility = View.VISIBLE
                } else {
                    ll_stickview1.visibility = View.GONE
                }
            }
        })
        RxView.clicks(hearderview.findViewById(R.id.tv_typenormal)).subscribe(Consumer {
            run {
                var intent = Intent(activity, HourseListActivity::class.java)
                intent.putExtra(AppKey.EXTRA_DATA,3)
                launchActivity(intent)
            }
        })
        RxView.clicks(hearderview.findViewById(R.id.tv_typemap)).subscribe(Consumer {
            run {
                var intent = Intent(activity, MapActivity::class.java)
                intent.putExtra(AppKey.EXTRA_ID,3)
                launchActivity(intent)
            }
        })
        RxView.clicks(hearderview.findViewById(R.id.tv_city)).subscribe({CitySelectActivity.startCitySelectActivity(activity)})
        RxView.clicks(tv_city).subscribe({CitySelectActivity.startCitySelectActivity(activity)})
        RxView.clicks(hearderview.findViewById(R.id.tv_decpic)).subscribe({DecorateActivity.startDecorateActivity(activity,0)})
        RxView.clicks(hearderview.findViewById(R.id.tv_deccompany)).subscribe({DecorateActivity.startDecorateActivity(activity,1)})
        RxView.clicks(et_search).subscribe({startActivity(Intent(activity,SearchActivity::class.java))})
        RxView.clicks(hearderview.findViewById(R.id.et_search)).subscribe({startActivity(Intent(activity,SearchActivity::class.java))})
    }

    override fun initbanner(bannerdata: AdBean) {
        if (bannerdata.list==null||bannerdata.list.size==0){
            hearderview.findViewById(R.id.zoom_image_view).visibility=View.VISIBLE
            hearderview.findViewById(R.id.rl_banner).visibility=View.GONE
            return
        }else{
            hearderview.findViewById(R.id.zoom_image_view).visibility=View.GONE
            hearderview.findViewById(R.id.rl_banner).visibility=View.VISIBLE
            var img=AdBean.ListEntity.ImagesEntity()
            img.imgdrawable=R.drawable.img
            img.img_path=""
            img.go_url=""
            bannerdata.list[0].images.add(0,img)
        }
        (hearderview.findViewById(R.id.tvtitle) as TextView).setText(bannerdata.list[0].title)

        (hearderview.findViewById(R.id.adbanner) as ConvenientBanner<AdBean.ListEntity.ImagesEntity>).setOnItemClickListener(object : OnItemClickListener{
            override fun onItemClick(position: Int) {
                if (TextUtils.isEmpty(bannerdata.list[0].images[position].go_url)){
                    return
                }
                WebViewActivity.startWebView(activity,"",bannerdata.list[0].images[position].go_url)
            }
        })
        ( hearderview.findViewById(R.id.adbanner) as ConvenientBanner<AdBean.ListEntity.ImagesEntity>).setPages(object :CBViewHolderCreator<AdHolderView>{
            override fun createHolder(): AdHolderView {
                return AdHolderView()
            }
        },bannerdata.list[0].images).startTurning(3000).setPageIndicator(intArrayOf(R.drawable.ic_page_indicator,R.drawable.ic_page_indicator_focused))
        //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)
                .isCanLoop=true
        (hearderview.findViewById(R.id.tvtitle) as TextView).visibility=View.GONE
        adbanner.onPageChangeListener=object :ViewPager.OnPageChangeListener{
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }
            override fun onPageSelected(position: Int) {
                if (position==0){
                    (hearderview.findViewById(R.id.tvtitle) as TextView).visibility=View.GONE
                }else{
                    (hearderview.findViewById(R.id.tvtitle) as TextView).visibility=View.VISIBLE
                }
            }

        }
        adbanner.setcurrentitem(0)
    }

    override fun showPopAdview(adBean: AdBean) {
        if (popwinow!=null){
            return
        }
        var contentview=View.inflate(activity,R.layout.popwindow_ad,null)
        Observable.just(adBean).subscribe ({
//            (contentview.findViewById(R.id.ivad) as ImageView).loadImgwithloading(Apputils.Utils.getImgUrl(adBean.list[0].images[0].img_path))
        Glide.with(context).load(Apputils.Utils.getImgUrl(adBean.list[0].images[0].img_path)).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(contentview.findViewById(R.id.ivad) as ImageView)
        },{t: Throwable? -> t!!.printStackTrace() })
        popwinow=CustomPopupWindow.builder()
                .parentView(rv_hourse)
                .contentView(contentview)
                .animationStyle(R.style.mypopwindow_anim_style)
                .customListener(object : CustomPopupWindow.CustomPopupWindowListener{
                    override fun initPopupView(contentView: View?) {
                        RxView.clicks(contentView!!.findViewById(R.id.iv_greenclose)).subscribe { popwinow!!.dismiss() }
                        RxView.clicks(contentView!!.findViewById(R.id.ivad)).subscribe ({
                            popwinow!!.dismiss()
                            if(TextUtils.isEmpty(adBean.list[0].images[0].go_url)){
                                return@subscribe
                            }
                            WebViewActivity.startWebView(activity,adBean.list[0].title,adBean.list[0].images[0].go_url)
                        },{})
                    }
                })
                .isWrap(false)
                .build()
        popwinow!!.setClippingEnabled(false)
        popwinow!!.show()
        Observable.timer(500,TimeUnit.MICROSECONDS).subscribeOn(AndroidSchedulers.mainThread()).observeOn(AndroidSchedulers.mainThread()).subscribe({ t ->run{
            BounceAnimation(contentview.findViewById(R.id.ivad))
                    .setBounceDistance(30.toFloat())
                    .setNumOfBounces(3)
                    .setDuration(500)
                    .animate()
        }  })
        popwinow!!.setOnDismissListener {
            var lp=activity.window.attributes
            lp.alpha=1f
            activity.window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            activity.window.attributes=lp
        }
        var lp=activity.window.attributes
        lp.alpha=1f
        activity.window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        activity.window.attributes=lp
    }

    fun setStatusBar(mImmersionBar:ImmersionBar){
        mImmersionBar.reset().statusBarDarkFont(true, 0.2f).init()
    }
    //    设置专题入口
    override fun setTopicEnter(rsp: BaseListData<TopicEnterBean>,isvisiable:Boolean) {
            if (isvisiable){
                hearderview.findViewById(R.id.ll_topic).visibility=View.VISIBLE
                bindData(rsp.list[0],hearderview.findViewById(R.id.iv_enter1) as ImageView)
                bindData(rsp.list!![1],hearderview.findViewById(R.id.iv_enter2) as ImageView)
            }else{
                hearderview.findViewById(R.id.ll_topic).visibility=View.GONE
            }

    }

    fun bindData(topic:TopicEnterBean,iv:ImageView){
        Glide.with(activity).load(topic.thumb).dontTransform().dontAnimate().into(iv)
//        iv.loadImgwithloading(topic.thumb)
        iv.setOnClickListener {
            when(topic.groupId){
            "10","2"->run{
                var info=InfoBean()
                info.go_url=topic.go_url
                info.title=topic.title
                info.thumb=topic.thumb
                info.is_self=1
                if (info.go_url.contains("zhuanti")){
                    info.topic_sign="1"
                }
                info.sources="觅窝"

                NewsWebActivity.startInfoActivity(activity,info)
            }
            "1","8","9"->run{
                var home=HomeBean()
                home.three_url=topic.go_url
                home.go_url=topic.go_url
                home.name=topic.title
                home.thumb=topic.thumb
                home.sources="觅窝"
                HomeWebActivity.startHomeActivity(activity,home)
            }
            "7"->run{
                WebViewActivity.startWebView(activity,topic.title,topic.go_url)
            }
            "6"->run{
//                var video=VideoBean()
//                video.go_url=topic.go_url
//                video.
                return@run
            }
        } }


    }
}